<?php
namespace model;
require_once __DIR__.'/../utils/MysqlDBUtils.php';
use utils\MysqlDBUtils;
use utils\PasswordUtils;

class UserModel {
    private $dbUtil;

    public function __construct() {
        $this->dbUtil = new MysqlDBUtils();
    }

    // 获取带分页和搜索的用户列表
    public function getPaginatedUsers($q = '', $currentPage = 1, $perPage = 8) {
        $whereCondition = '';
        if (!empty($q)) {
            $qLike = "%{$q}%";
            $whereCondition = "WHERE username LIKE '{$qLike}' OR email LIKE '{$qLike}'";
        }

        // 查询总记录数
        $totalSql = "SELECT COUNT(*) AS total FROM user {$whereCondition}";
        $totalResult = $this->dbUtil->prepareQuery($totalSql);
        $total = $totalResult ? $totalResult[0]['total'] : 0;

        // 计算分页偏移量
        $offset = ($currentPage - 1) * $perPage;
        $sql = "SELECT * FROM user {$whereCondition} LIMIT {$offset}, {$perPage}";
        $users = $this->dbUtil->prepareQuery($sql);

        return [
            'users' => $users,
            'total' => $total,
            'currentPage' => $currentPage,
            'perPage' => $perPage,
            'totalPages' => ceil($total / $perPage)
        ];
    }

    // 新增用户
    public function addUser($data)
    {
    $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
    $sql = "INSERT INTO user (username, role, password, name, phone, create_time,email) VALUES (?, ?, ?, ?, ?,NOW(),?)";
        $params = [
            $data['username'],
            $data['role'],
            $hashedPassword,
            $data['name'],
            $data['phone'],
            $data['email']
        ];
        return $this->dbUtil->prepareExecute($sql, $params);
    }

    /**
     * 更新用户信息
     * @param int $userId 用户ID
     * @param array $userData 更新数据
     * @param int $passwordUpdated 密码是否被修改（1=修改，0=未修改）
     * @return int 更新结果
     */
    public function updateUser(int $userId, array $userData, int $passwordUpdated): int
    {
        $db = new MysqlDBUtils();
        $updateFields = [];
        $params = [];

        // 基础字段更新
        $updateFields = [
            'username = ?',
            'name = ?',
            'phone = ?',
            'email = ?',
            'role = ?'
        ];
        $params = [
            $userData['username'],
            $userData['name'],
            $userData['phone'],
            $userData['email'],
            $userData['role']
        ];

        // 密码更新逻辑（仅当用户修改了密码时执行）
        if ($passwordUpdated === 1) {
            $updateFields[] = 'password = ?';
            $params[] = PasswordUtils::hash($userData['password']); // 调用工具类哈希密码
        }

        // 构建最终SQL
        $sql = "UPDATE user SET " . implode(', ', $updateFields) . " WHERE id = ?";
        $params[] = $userId;

        return $this->dbUtil->prepareExecute($sql, $params);

    }

    // 删除用户
    public function deleteUser($id): array
    {
        $sql = "DELETE FROM user WHERE id=?";
        return $this->dbUtil->prepareExecute($sql, [$id]);
    }

    //根据用户名查询用户
    public function getUserByUsername(string $username): ?array {
        $sql = "SELECT * FROM user WHERE username = ?";
        $result = $this->dbUtil->prepareExecute($sql, [$username]);
        return $result ? $result[0] : null;
    }

    public function getAllUsers(): array {
        $sql = "SELECT * FROM user";
        $result = $this->dbUtil->prepareQuery($sql);
        return $result ? $result : [];
    }
}